package com.bookbuf.module.manager;

import android.util.Log;

import com.bookbuf.module.exception.StubException;
import com.bookbuf.module.stub.Stub;
import com.bookbuf.module.stub.impl.BizProxyStub;

import java.util.concurrent.ConcurrentHashMap;

/**
 * author: robert.
 * date :  2016/12/29.
 */

public class StubManager {

    private static final String TAG = "StubManager";
    private static StubManager manager = new StubManager();

    public static StubManager getManager() {
        return manager;
    }

    private ConcurrentHashMap<Class<?>, Stub> map = new ConcurrentHashMap<>();

    private boolean containsKey(Class<?> clazz) {
        return map.containsKey(clazz);
    }

    private Stub get(Class<?> clazz) {
        Stub stub = map.get(clazz);
        Log.i(TAG, "get: " + clazz.getSimpleName() + ":" + stub);
        return stub;
    }

    private void put(Class<?> clazz, Stub stub) {
        map.put(clazz, stub);
        Log.i(TAG, "put: " + clazz.getSimpleName() + ":" + stub);
    }

    public BizProxyStub obtain(BizProxyStub.BizDependence dependence) {
        final Class<?> clazz = BizProxyStub.class;
        if (containsKey(clazz)) {
            return (BizProxyStub) get(clazz);
        } else {
            BizProxyStub stub = BizProxyStub.asInterface(dependence);
            put(clazz, stub);
            return obtain(dependence);
        }
    }

    public BizProxyStub obtainPrivate() {
        final Class<?> clazz = BizProxyStub.class;
        if (containsKey(clazz)) {
            return (BizProxyStub) get(clazz);
        } else {
            throw new StubException("在模块内部引用到外部依赖，必须在外部预先注入数据!");
        }
    }

}
